import { Component, OnInit, ViewChild } from '@angular/core';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema, SFTransferWidgetSchema } from '@delon/form';
import { DictService } from '@core';
import { map } from 'rxjs/operators';
import { environment } from '@env/environment';

@Component({
  selector: 'app-sys-user-edit',
  templateUrl: './edit.component.html',
})
export class SysUserEditComponent implements OnInit {
  record: any = {};
  i: any;
  schema: SFSchema = {
    properties: {
      username: { type: 'string', title: '用户名', maxLength: 30 },
      petname: { type: 'string', title: '昵称', maxLength: 30 },
      realname: { type: 'string', title: '真实姓名', maxLength: 30 },
      gender: {
        type: 'string',
        title: '性别',
        maxLength: 15,
        ui: {
          widget: 'radio',
          asyncData: () => this.dictService.getSFSchemaEnumTypes('GENDER'),
          default: 'N',
        },
      },
      birthday: { type: 'string', title: '生日', maxLength: 15, format: 'date' },
      phone: { type: 'string', title: '电话', maxLength: 15, format: 'mobile' },
      email: { type: 'string', title: '邮箱', maxLength: 40, format: 'email' },
      roleIds: { type: 'string', title: '角色', maxLength: 15 },
    },
    required: ['username', 'roleIds'],
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
    $roleIds: {
      grid: { span: 24 },
      widget: 'transfer',
      titles: ['未拥有', '已拥有'],
      asyncData: () =>
        this.http.get(`${environment.sys.ctx}/sysRole/findAll`).pipe(
          map(items => {
            const options: any[] = [];
            items.forEach((element: any) => {
              options.push({ title: element.name, value: element.id });
            });
            return options;
          }),
        ),
    },
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private dictService: DictService,
  ) {}

  ngOnInit(): void {
    if (this.record.id) {
      this.schema.properties!.username.readOnly = true;
      this.http.get(`${environment.sys.ctx}/sysUser/${this.record.id}`).subscribe(res => {
        this.i = res;
        this.i.roleIds = [];
        this.i.roles.forEach((it:any) => this.i.roleIds.push(it.id));
      });
    } else {
      this.ui.$username = {
        validator: (value: any) =>
          this.http
            .get(`${environment.sys.ctx}/sysUser/isUnique/${value}`)
            .pipe(map(res => (!res ? [{ keyword: 'required', message: '用户名已存在' }] : []))),
      };
    }
  }

  save(value: any) {
    value.roles = [];
    value.roleIds.forEach((roleId: any) => value.roles.push({ id: roleId }));
    this.http.put(`${environment.sys.ctx}/sysUser`, value).subscribe(res => {
      this.msgSrv.success('保存成功');
      this.modal.close(true);
    });
  }

  close() {
    this.modal.destroy();
  }
}
